package com.itheima.web.controller;

import com.itheima.domain.User;
import com.itheima.ModuleService;
import com.itheima.UserService;
import com.itheima.web.filters.BeanFactory;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/authentication/*")
public class AuthenticationServlet extends BaseServlet{
    //获取service对象
    private UserService userService= BeanFactory.getBean("userService",UserService.class);
    private ModuleService moduleService = BeanFactory.getBean("moduleService",ModuleService.class);

    /**
     * 处理用户登录的请求
     * @return
     */
    private void login(HttpServletRequest request, HttpServletResponse response){
        try {
            //1 获取请求参数邮箱和密码
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            //2 调用service，获取用户信息
            User user=userService.login(email,password);
            //3 判断是否登录成功
            if(user!=null){
                //4 如果登录成功，保存用户信息到session中，响应结果
                request.getSession().setAttribute("user",user);
//              查询用户具有的操作权限，保存到session中，等待权限验证
                List<String> curls=moduleService.findPermissionByUserId(user.getId());
                String sendRedirect = (String) request.getSession().getAttribute("sendRedirect");
            if (!StringUtils.isBlank(sendRedirect)){
                response.sendRedirect(sendRedirect);
            } else {
                response.sendRedirect(request.getContextPath()+"/pages/main.html");

            }
            }else {
                //5 如果登录失败，响应失败的结果
                response.sendRedirect(request.getContextPath()+"/login.html");
            }
             }catch (Exception e) {
            e.printStackTrace();

        }
    }

    private void logout(HttpServletRequest request,HttpServletResponse response) throws IOException {
//        销毁session
        request.getSession().invalidate();
//        重定向到登录页面
        response.sendRedirect(request.getContextPath()+"/login.html");
    }
}